package com.tiktok.service.impl;

import com.tencentcloudapi.tms.v20201229.models.User;
import com.tiktok.base.BaseInfoProperties;
import com.tiktok.enums.MessageEnum;
import com.tiktok.mo.MessageMO;
import com.tiktok.pojo.Users;
import com.tiktok.repository.MessageRepository;
import com.tiktok.service.MsgService;
import com.tiktok.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *
 * </p>
 *
 * @author 老顾
 * @since 2023-05-25
 */
@Service
public class MsgServiceImpl extends BaseInfoProperties implements MsgService {

    @Resource
    private MessageRepository messageRepository;

    @Resource
    private UserService userService;

    @Override
    public void createMsg(String fromUserId,
                          String toUserId,
                          Integer type,
                          Map msgContent) {

        Users user = userService.getUser(fromUserId);

        MessageMO messageMO = new MessageMO();

        messageMO.setFromUserId(fromUserId);
        messageMO.setFromNickname(user.getNickname());
        messageMO.setFromFace(user.getFace());
        messageMO.setToUserId(toUserId);
        messageMO.setMsgType(type);

        if (msgContent != null) {
            messageMO.setMsgContent(msgContent);
        }

        messageMO.setCreateTime(new Date());

        messageRepository.save(messageMO);
    }

    @Override
    public List<MessageMO> queryList(String userId,
                                     Integer page,
                                     Integer pageSize) {

        Pageable pageable = PageRequest.of(page, pageSize, Sort.Direction.DESC,"createTime");

        List<MessageMO> list = messageRepository.findAllByToUserIdEqualsOrderByCreateTimeDesc(userId, pageable);

        for (MessageMO msg : list) {

            // 如果类型是关注消息，则需要查询我之前有没有关注过他，用于在前端标记"互粉""互关"
            if (msg.getMsgType() != null && Objects.equals(msg.getMsgType(), MessageEnum.FOLLOW_YOU.type)) {
                Map map = msg.getMsgContent();
                if (map == null) {
                    map = new HashMap();
                }

                String relationship = redis.get(REDIS_FANS_AND_VLOGGER_RELATIONSHIP + ":" + msg.getToUserId() + ":" + msg.getFromUserId());
                if (StringUtils.isNotBlank(relationship) && relationship.equalsIgnoreCase("1")) {
                    map.put("isFriend", true);
                } else {
                    map.put("isFriend", false);
                }
                msg.setMsgContent(map);
            }
        }
        return list;
    }
}
